package cn.com.smart.module.system.notice.controller;

import cn.com.smart.common.utils.security.ShiroUtils;
import cn.com.smart.framework.aspectj.lang.annotation.Log;
import cn.com.smart.framework.aspectj.lang.enums.BusinessType;
import cn.com.smart.framework.web.controller.BaseController;
import cn.com.smart.framework.web.domain.AjaxResult;
import cn.com.smart.framework.web.page.TableDataInfo;
import cn.com.smart.module.monitor.noticeLog.domain.SysNoticeLog;
import cn.com.smart.module.monitor.noticeLog.service.ISysNoticeLogService;
import cn.com.smart.module.system.notice.domain.Notice;
import cn.com.smart.module.system.notice.service.INoticeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 公告 信息操作处理
 * 
 */
@Controller
@RequestMapping("/system/notice")
public class NoticeController extends BaseController
{
    private String prefix = "system/notice";

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private ISysNoticeLogService noticeLogService;

    @RequiresPermissions("system:notice:view")
    @GetMapping()
    public String notice()
    {
        return prefix + "/notice";
    }

    /**
     * 查询公告列表
     */
    @RequiresPermissions("system:notice:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Notice notice)
    {
        startPage();

        List<Long> noticeIds=notReadNoticeNum(ShiroUtils.getUserId());
        List<Notice> list = noticeService.selectNoticeList(notice);

        for (Notice fornotice : list){
            for (Long noticeId : noticeIds){
                if (fornotice.getNoticeId() == noticeId){
                    fornotice.setReadState(1);
                    break;
                }else {
                    fornotice.setReadState(0);
                }
            }

        }

        return getDataTable(list);
    }

    /**
     * 新增公告
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存公告
     */
    @RequiresPermissions("system:notice:add")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Notice notice)
    {
        return toAjax(noticeService.insertNotice(notice));
    }

    /**
     * 修改公告
     */
    @GetMapping("/edit/{noticeId}")
    public String edit(@PathVariable("noticeId") Long noticeId, ModelMap mmap)
    {
        mmap.put("notice", noticeService.selectNoticeById(noticeId));
        return prefix + "/edit";
    }

    /**
     * 查询公告
     */
    @GetMapping("/browse/{noticeId}")
    public String browse(@PathVariable("noticeId") Long noticeId, ModelMap mmap)
    {

        List<Long> noticeIdList=new ArrayList<>();
        SysNoticeLog noticeLog=noticeLogService.selectSysNoticeLogById(ShiroUtils.getUserId());

        /*逻辑判断，该用户是否浏览过*/
        if (noticeLog == null){
            SysNoticeLog noticeLogs=new SysNoticeLog();
            noticeIdList.add(noticeId);

            //添加进数据库
            noticeLogs.setUserId(ShiroUtils.getUserId());
            noticeLogs.setMessageidList(JSON.toJSONString(noticeIdList));
            noticeLogService.insertSysNoticeLog(noticeLogs);

        }else {

            try {

                //json字符串转set,并添加公告ID
                String ids=noticeLog.getMessageidList();
                Set<Long> idslist= JSON.parseObject(ids,new TypeReference<Set<Long>>(){});

                idslist.add(noticeId);

                //添加进数据库，set转Json字符串
                noticeLog.setUserId(ShiroUtils.getUserId());
                noticeLog.setMessageidList(JSON.toJSONString(idslist));
                noticeLogService.updateSysNoticeLog(noticeLog);

            }catch (Exception e){
                System.out.println("该用户以查看这条公告，无需增加记录");
            }
        }

        mmap.put("notice", noticeService.selectNoticeById(noticeId));
        return prefix + "/detail";
    }

    /**
     * 修改保存公告
     */
    @RequiresPermissions("system:notice:edit")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Notice notice)
    {
        return toAjax(noticeService.updateNotice(notice));
    }

    /**
     * 删除公告
     */
    @RequiresPermissions("system:notice:remove")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(noticeService.deleteNoticeByIds(ids));
    }


    /**
     * 获取用户未读信息
     * @return
     */
    @RequestMapping("/notReadNotice")
    @ResponseBody
    public AjaxResult notReadNotice(){

        JSONObject jsonObject=new JSONObject();

        List<Long> notReadNotices=notReadNoticeNum(ShiroUtils.getUserId());
       int notReadNume=notReadNotices.size();

       List<Notice> infors=new ArrayList<>();


       /*没查阅公告大于3条，只取前3条*/
       if (notReadNume > 3){

           List<Long> befor3 = notReadNotices.subList(0,3);

           for (Long id :befor3){
               infors.add(noticeService.selectNoticeById(id));
           }

           jsonObject.put("NoticeTitle",infors);
       }else {

           for (Long id :notReadNotices){
               infors.add(noticeService.selectNoticeById(id));
           }

           jsonObject.put("NoticeTitle",infors);
       }

        jsonObject.put("notReadNume",notReadNume);
       return AjaxResult.success(jsonObject);

    }



    /**
     * 计算该登陆用户有多少未查看信息
     * @param userId
     * @return
     */
    public List<Long> notReadNoticeNum(Long userId){

        SysNoticeLog noticeLog=noticeLogService.selectSysNoticeLogById(userId);
        
        /*所有公告的ID*/
        List<Long> noticeNums=noticeService.noticeIdList();

        /*如果查询不到该用户，则返回所有公告资料*/
        if (noticeLog == null){
            return noticeNums;
        }

        /*用户以查询公告的ID*/
        List<Long> noticeNumeds= JSON.parseObject(noticeLog.getMessageidList(),new TypeReference<List<Long>>(){});

        /*2数组去重,并统计*/
        noticeNums.removeAll(noticeNumeds);

        return noticeNums;
    }
}
